$m(function() {
	var that = this;
	var $this = this.element;

	var page = $("#tempo-mine-algorithms");
	var grid = $(".user-defined-algorithm-list");
	
	/**
	 * 初始化
	 */
	var init = function(){
		initLayout();
		renderGrid();
		bindEvent();
	}
	
	/**
	 * 初始化布局
	 */
	var initLayout = function(){
		page.layout({
			north : {
				resizable : false,
				size : 50,
				spacing_open : 0,
				closable : false
			},
			center:{
				onresize:TempoUtils.throttle(function(){
					grid.datagrid("resize");
				},200,true) 
			}
		});
	}
	
	/**
	 * 绘制列表
	 */
	var renderGrid = function(){
		var colName = [TempoUtils.locale("mine.classification"),TempoUtils.locale("mine.suanfamingcheng2"),TempoUtils.locale("mine.suanfajieshao"),TempoUtils.locale("mine.publish-mine-job-grid-col-status"),TempoUtils.locale("mine.publish-mine-job-grid-col-opt")];
		var colModel = [{name: "subType", sortable:false, formatter: subTypeFormatter,align : 'center'},
		                {name: "name", sortable:false,align : 'center'},
		                {name: "remark", sortable:false,align : 'center'},
		                {name: "status", sortable:false, formatter: statusFormatter,align : 'center'},
		                {name: "action", sortable:false, formatter: action,align : 'center'}
		];
		var postdata = {};
		grid.datagrid({
			   fit: true, 
	           datatype: "json",
	           url: contextPath +　"/api/ai/personal/listAllAlgorithm",
	           colNames: colName,
	           colModel: colModel,
	           rowNum : 20,
	           rownumbers: true,
	           pagination: true,
	           multiselect: false,
	           shrinkToFit : true, 
	           onSelectRow : function(rowId){
	        	   
	           },
	           toolbar:[{
					id : "ag_grid_btn_add",
					text : TempoUtils.locale("mine.xinzengsuanfa"),
					icon : "ui-icon tempo-ui-icon-white tempo-ui-icon-add",
					click : addAG
			    }],
		       postData : postdata
		    });
	}
	var addAG = function(){
		uploadData = {};
		openUploadDialog();
		return false;
	}
	/**
	 * 弹出上床算法界面对话框，选择要上传的算法包，上传提取算法信息并进行展示，确定无误后则进行发布申请
	 */
	var openUploadDialog= function(edit, id) {
		$(".user-defined-edit-dailog").remove();
		$("#pop-sf").empty();
		$("#pop-sf").append("<div class='user-defined-edit-dailog'><form class='user-defined-upload-form' ><table><tr>"
			+"<td><label>"+TempoUtils.locale( "mine.suanfawenjian")+"</label><input class=\"user-defined-upload-name\" readonly=true/> <span class='user-defined-upload' /> </td>"
			+'</tr></table></form><fieldset class="tempo-fieldset">'
		+"<legend>"+TempoUtils.locale( "mine.suanfajibenxinxi")+"</legend>"
		+"<table class=\"formLayout user-defined-algorithm-info\">"
		+"	<tr><td><label>"+TempoUtils.locale( "mine.suanfamingcheng")+"</label></td><td class='name text-value'></td></tr>"
		+"	<tr><td><label>"+TempoUtils.locale( "mine.suanfatubiao")+"</label></td><td class='image text-value'></td></tr>"
		+"	<tr><td><label>"+TempoUtils.locale( "mine.suanfafenlei")+"</label></td><td class='category text-value'></td></tr>"
		+"	<tr><td><label>"+TempoUtils.locale( "mine.suanfaleibie")+"</label></td><td class='lang text-value'></td></tr>"
		+"	<tr><td><label>"+TempoUtils.locale( "mine.shenqingren")+"</label></td><td class='username text-value'></td></tr>"
		+"	<tr><td><label>"+TempoUtils.locale( "mine.shenqingriqi")+"</label></td><td class=\"date text-value\"></td></tr>"
		+"	<tr><td><label>"+TempoUtils.locale( "mine.suanfamiaoxu")+"</label></td><td class=\"description text-value\"></td></tr>"
		+"</table></fieldset></div>");
		dialog = $("#pop-sf .user-defined-edit-dailog").dialog({
			modal : true,
			autoOpen : false,
			width : 460,
			height : 530,
			title : TempoUtils.locale("mine.zidingyisuanfafabushenqin"),
			resizable : false,
			close : function() {
				$('.user-defined-upload input').upload('destroy');
				$('.user-defined-upload').empty();
			},
			open : function() {
				uploadData = {};
				initForm();
				if(!edit) {
					$('.user-defined-upload-form').show();
					var upload = $('.user-defined-upload');
					upload.empty();
					var uploader = $('<input>').appendTo(upload);
					uploader.upload({
						text: TempoUtils.locale("mine.flow_choose"),
						name: 'userFile',
						width: 60,
						accept: '.jar',
						change: function(e, f) {
							uploadJar(e, f);
						}
					});
					//点击选择按钮时，默认禁用3秒
					var isUploadEnable = true;
					upload.find('input').on('click', function(e) {
						var e = $(this);
						var enable = true;
						if(isUploadEnable) {
							e.parents('.tempo-upload-container').addClass('tempo-upload-disable');
							setTimeout(function() {
								isUploadEnable = true
								e.parents('.tempo-upload-container').removeClass('tempo-upload-disable');
							}, 3000);
							isUploadEnable = false
						} else {
							enable = false;
						}
						return enable;
					});
					$('.user-defined-upload-form')
					.attr('enctype', 'multipart/form-data')
					.attr('method', 'post')
					.attr("action", contextPath + '/api/ai/personal/uploadJar');;
					$('.user-defined-upload-name').validatebox({
						readonly: true,
						value: ''
					});
				} else {
					$('#user-defined-dialog-save-btn').remove();
					$('.user-defined-upload-form').hide();
					$.post(contextPath + '/api/ai/personal/selectOne', {id: id}, function(data) {
						initForm(data, true);
					});
				}
			},
			buttons:[{
				text: TempoUtils.locale("mine.publish-dialog-sure"),
				id: 'user-defined-dialog-save-btn',
				click: function(){
					if(!$.isEmptyObject(uploadData)) {
						saveUploadJar();
					} else {
						$('<div>').alert({msg: TempoUtils.locale("mine.upload_alg_jar_empty")});
					}
				}
			}]
		}).dialog("open");
	}
	
	/**
	 * 初始化算法基本信息
	 */
	var initForm = function(data, full) {
		$('.user-defined-algorithm-info .text-value').empty();
		if(data) {
			var panel = $('.user-defined-algorithm-info');
			panel.find('.name').text(data.name || '');
			try{
				var v = TempoUtils.locale("mine." + data.subType);
				panel.find('.category').text(v);
			}catch(e){}
			panel.find('.lang').text(data.lang || '');
			panel.find('.username').text(data.userName || '');
			var d = DateUtils.formatDateTime(data.createDate);
			if(d || data.date) {
				panel.find('.date').parent().show();
				panel.find('.date').text(data.date || d).show();
			} else {
				panel.find('.date').parent().hide();
			}
			$('<textarea>').text(data.remark || '')
				.attr('readonly', true)
				.attr('title', data.remark || '')
				.appendTo(panel.find('.description'))
			var src = "";
			if(data.image) {
				src = contextPath + "/api/ai/personal/image?src=" + data.image + "&baseResPath=" + data.baseResPath;
			} else if(data.icon) {
				src = "data:image/png;base64," + data.icon
			} else if(data.id) {
				src = contextPath + "/api/ai/personal/image?id=" + data.id
			}
			$('<img>').attr('src', src).appendTo(panel.find('.image'));
			
		}
		if(full) {
			$('.user-defined-algorithm-info textarea').css('height', '150px');
		} else {
			$('.user-defined-algorithm-info textarea').css('height', '70px');
		}
	}
	
	/**
	 * 节点分类国际化显示
	 */
	var subTypeFormatter = function(val, row, rowData) {
		try{
			return TempoUtils.locale('mine.' + val);
		}catch(e){}
		return val;
	}
	/**
	 * 状态格式化
	 */
	var statusFormatter = function(val, row, rowData) {
		if(val == 'on') {
			return TempoUtils.locale("mine.yifabu");
		} else if(val == 'off'){
			return TempoUtils.locale("mine.weifabu");
		} else {
			return TempoUtils.locale("mine.unkown");
		}
	}
	var action = function(val, row, rowData) {
		var ac = "<div class='user-defined-list-action' title=''>";
		   ac += "	<span class='user-defined-edit-action ui-icon tempo-ui-icon tempo-ui-icon-textseek' uda-id='$id' title='"+TempoUtils.locale("mine.publish-published-flow-grid-optview")+"'></span>";
		   ac += "	<span class='user-defined-delete-action ui-icon tempo-ui-icon tempo-ui-icon-delete' uda-id='$id' title='"+TempoUtils.locale("mine.mine_del")+"'></span>";
		   ac += "</div>";
		ac = ac.replace(/\$id/g, rowData.id)
		return ac;
	}
	/**
	 * 上传算法包
	 */
	var uploadJar = function(e, f) {
		$('.user-defined-upload-name').val(f.file.name);
		var process = $("<div/>").tempoprogressbar();
		$('.user-defined-upload-form').ajaxSubmit({
			dataType:'json',
			type : 'post',
			beforeSubmit:function(result){
				return true; 
			},
			success:function(data){
				if(data.error) {
					$('<div>').alert({msg: data.error});
				} else {
					initForm(data);
					uploadData = $.extend(uploadData, data);
				}
			},
			complete: function(){
				if(process){
					process.tempoprogressbar('destroy');
				}
			},
			error:function( e ){
				process.tempoprogressbar("destroy");
				TempoUtils.uploadErrorHandler(e);
			}
		});
	}
	
	/**
	 * 保存上传的算法包
	 */
	var saveUploadJar = function() {
		var process = $("<div/>").tempoprogressbar();
		uploadData.tag = "API";
		$.post(contextPath + "/api/ai/personal/saveOrUpdate", uploadData, function(data) {
			process.tempoprogressbar('destroy');
			if(data.status == "true") {
				dialog.dialog('close');
				$('<div>').alert({msg: TempoUtils.locale("mine.baocunchenggong")});
				grid.datagrid('reloadGrid');
			} else {
				$('<div>').alert({msg: data.error});
			}
		})
	}
	var bindEvent = function() {
		$('.user-defined-datagrid').on('click', '.user-defined-edit-action', function(e) {
			var ui = $(this);
			var id = ui.attr('uda-id');
			openUploadDialog(true, id);
		});
		
		$('.user-defined-datagrid').on('click', '.user-defined-delete-action', function(e) {
			var ui = $(this);
			var id = ui.attr('uda-id');
			var deleteDialog = $('<div style="width:100%;height:100%;background-color: #ffffff"/></div>').appendTo($('body'));
			deleteDialog.dialog({
				modal : true,
				width : 420,
				height : 118,
				title : TempoUtils.locale("mine.prompt"),
				resizable : false,
				closeOnEscape : true,
				close:function(){
					deleteDialog.remove();
				},
				open : function(){
					debugger
					$('<div  class="tempo-sys-delete-dialog-content">'+TempoUtils.locale("mine.publish-mine-job-grid-col-delete-confirm")+'</div>').appendTo($(deleteDialog));
				},
				buttons:[{
					text:TempoUtils.locale("mine.publish-dialog-sure"),
					id: 'tempo-sys-ok-btn',
					click:function(){
						debugger
						var process = $("<div/>").tempoprogressbar();
						$.post(contextPath + "/api/ai/personal/remove?", {id: id,api:"API"}, function(d) {
							process.tempoprogressbar('destroy');
							if(d) {
								$('<div>').alert({msg: TempoUtils.locale("mine.shanchuchenggong")});
								deleteDialog.dialog("close");
								grid.datagrid('reloadGrid');
							} else {
								$('<div>').alert({msg: TempoUtils.locale("mine.shanchushibaizidingyi")});
							}
						} );
					}
				},{
					text:TempoUtils.locale("mine.publish-dialog-cancel"),
					id: 'tempo-sys-cancel-btn',
					click:function(){
						deleteDialog.dialog("close");
					}
				}]
			})
		})
	}
	init();
});